<!--
 * Tencent is pleased to support the open source community by making Tars available.
 *
 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * https://opensource.org/licenses/BSD-3-Clause
 *
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="../css/bootstrap.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <!--[if lt IE 9]>
    <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script src="../js/jquery.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
    <script src="../js/template.js"></script>
    <script src="../js/common.js"></script>
</head>
<body>
<div class="content">
    <h4 class="sub-header">服务列表</h4>
    <div class="tool-bar">
        <div class="btn-group">
            <button type="button" class="btn btn-sm btn-primary" onclick="deployService()">发布选中节点</button>
        </div>
        <div class="fr">
            <a href="#;" id="his-link" class="btn btn-sm btn-default">发布历史</a>
        </div>
    </div>
    <div id="patch-server-list" class="mt10"></div>
</div>

<!--上传发布包-->
<div id="dlg-upload-patch" class="form-horizontal" style="display:none">
    <form enctype="multipart/form-data" id="uploadForm">
        <input type="hidden" name="application" id="up-application" value="">
        <input type="hidden" name="module_name" id="up-server-name" value="">
        <div class="form-group">
            <div class="col-sm-2"><label class="tr wp100 control-label">发布包</label></div>
            <div class="col-sm-10">
                <input id="file" type="file" name="suse" class="form-control"/>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-2"><label class="tr wp100 control-label">备注</label></div>
            <div class="col-sm-10">
                <textarea name="comment" id="" class="form-control" rows="3"></textarea>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-2"></div>
            <div class="col-sm-10">
                <button type="button" id="upload" class="btn btn-primary btn-sm">上传</button>
            </div>
        </div>
    </form>
</div>

<div id="dlg-ret" style="display:none">

</div>

<div id="dlg-patch" class="form-horizontal" style="display: none">
    <div class="form-group">
        <div class="col-sm-2"><label class="tr wp100 control-label">应用·服务</label></div>
        <div class="col-sm-10">
            <div id="p-server-name"></div>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-2"><label class="tr wp100 control-label">待发布节点</label></div>
        <div class="col-sm-10">
            <ul id="node-list"></ul>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-2"><label class="tr wp100 control-label">选择发布版本</label></div>
        <div class="col-sm-10">
            <select name="" id="version-select" class="form-control">
                <option value="">请选择</option>
            </select>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-2"></div>
        <div class="col-sm-10">
            <button type="button" class="btn btn-sm btn-default" onclick="openUploadDlg()"><i class="glyphicon glyphicon-upload"></i> 上传发布包</button>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-2"><label class="tr wp100 control-label">备注</label></div>
        <div class="col-sm-10">
            <textarea name="" id="comment" class="form-control" rows="3"></textarea>
        </div>
    </div>
</div>



<script type="text/html" id="patch-service-tpl">
    <table class="table table-bordered" id="patch-service-table">
        <thead>
        <tr>
            <th><label><input type="checkbox" onchange="checkAll(this)"></label></th>
            <th>节点</th>
            <th>启用Set</th>
            <th>Set名</th>
            <th>Set区域</th>
            <th>Set组</th>
            <th>设置状态</th>
            <th>当前状态</th>
            <th>版本</th>
            <th>发布时间</th>
        </tr>
        </thead>
        <tbody>
        {{each data as it}}
        <tr>
            <td><label><input type="checkbox" class="chks" data-bak="{{it.bak_flag}}" data-app="{{it.application}}" data-server="{{it.server_name}}" data-node="{{it.node_name}}" value="{{it.id}}"></label></td>
            <td>{{it.node_name}}</td>
            <td>{{if it.enable_set=='true'}}是{{else}}否{{/if}}</td>
            <td>{{it.set_name}}</td>
            <td>{{it.set_area}}</td>
            <td>{{it.set_group}}</td>
            <td>{{if it.setting_state=='active'}}<span class="label label-success">active</span>{{else}}<span class="label label-danger">inactive</span>{{/if}}</td>
            <td class="get_curr_status" data-serviceid="{{it.id}}"></td>
            <td>{{it.patch_version}}</td>
            <td>{{it.patch_time}}</td>
        </tr>
        {{/each}}
        </tbody>
        <tfoot>
            <tr><td class="tpage" colspan="10"></td></tr>
        </tfoot>
    </table>
</script>




<script>
    var treeId = parent.tarsTree.treeId ? parent.tarsTree.treeId : getQueryStringArgs().treeId,
            params = treeId.split('.'),
            paramMap = {};
    var gData = {};
    $.each(params,function (index,n) {
        paramMap[n.substring(0,1)] = n.substring(1);
    });
    gData.level = params[params.length-1].substring(0,1);

    if(gData.level==1){
        $('body').html('<div class="alert alert-info mt10">发布管理只管理服务层级，请您先在左侧业务树选择服务。</div>');
    }else{
        getService();
    }

    $('#upload').on('click',function () {
        showLoading();
        $.ajax({
            url: '/pages/server/api/upload_patch_package',
            type: 'POST',
            cache: false,
            data: new FormData($('#uploadForm')[0]),
            processData: false,
            contentType: false
        }).done(function(data) {
            removeLoading();
            closeErrorMsg();
            var $dlg = $('#dlg-upload-patch');
            if(data.ret_code==200){
                $dlg.parents('.modal').modal('hide');
                getPatchList($('#version-select'),$('#up-application').val(),$('#up-server-name').val());
            }else{
                showErrorMsg($dlg,'上传发布包失败');
            }
        });
    });


    /**
     * 获取服务列表
     */
    function getService() {
        $.getJSON('/pages/server/api/server_list?tree_node_id='+parent.tarsTree.treeId,function (data) {
            $.each(data.data,function (index,n) {
                n.bak_flag = n.bak_flag.toString();
                n.enable_set = n.enable_set.toString();
            });
            var htmlStr = template('patch-service-tpl',data);
            $('#patch-server-list').html(htmlStr);
            $('#patch-service-table').table();
            $('.get_curr_status').each(function () {
                var $self = $(this);
                getServiceCurrStatus($self.attr('data-serviceid'),$self);
            });
            if(data.data && data.data.length){
                $('#his-link').attr('href','history_list.html?application='+data.data[0].application+'&server_name='+data.data[0].server_name);
            }
        });
    }

    /**
     * 获取服务实时状态
     * @param {String} id 服务ID
     * @param {Element} tar 目标
     */
    function getServiceCurrStatus(id,tar) {
        $.getJSON('/pages/server/api/get_realtime_state?id='+id,function(data){
            if(data.ret_code==200){
                if(data.data.realtime_state=='inactive'){
                    tar.html('<span class="label label-danger">inactive</span>');
                }else{
                    tar.html('<span class="label label-success">active</span>');
                }
            }else{
                tar.html('<span class="label label-danger">inactive</span>');
            }
        });
    }

    /**
     * 打开上传发布包弹出框
     */
    function openUploadDlg() {
        var chks = $('#patch-server-list').find('.chks:checked').eq(0);
        if(!chks.length) {
            closeErrorMsg();
            showErrorMsg($('body'),'请至少选择一个服务节点');
            return;
        }
        var $box = $('#dlg-upload-patch');
        $box.find('#up-application').val(chks.data('app'));
        $box.find('#up-server-name').val(chks.data('server'));
        showDialog($box,'上传发布包');
    }

    /**
     * 获取发布版本列表
     * @param {Element} tar         下拉框
     * @param {String} appName      应用名
     * @param {String} serverName   服务名
     */
    function getPatchList(tar,appName,serverName) {
        $.getJSON('/pages/server/api/server_patch_list?application='+appName+'&module_name='+serverName,function (data) {
            if(data.ret_code==200 && data.data.length){
                var htmlStr = '';
                $.each(data.data,function (index,n) {
                    var commentStr = '';
                    if(n.comment && n.comment.length>20){
                        commentStr = n.comment.substring(0,20)+'...';
                    }else{
                        commentStr = n.comment
                    }
                    htmlStr += '<option value="'+n.id+'">'+ n.id + ' | ' + n.posttime + ' | ' + commentStr +'</option>';
                });
                tar.html(htmlStr);
            }
        });
    }

    /**
     * 发布服务
     */
    function deployService() {
        var chks = $('#patch-server-list').find('.chks:checked'),
            paramArr = [],paramObj={},htmlStr = '';
        var $box = $('#dlg-patch');
        closeErrorMsg();
        if(!chks.length){
            showErrorMsg($('body'),'请至少选择一个服务节点');
            return;
        }
        chks.each(function () {
            htmlStr += '<li>'+$(this).data('node')+'</li>';
        });
        $('#node-list').html(htmlStr);

        $box.find('#p-server-name').html($(chks[0]).data('server'));
        getPatchList($('#version-select'),$(chks[0]).data('app'),$(chks[0]).data('server'));
        showDialog($box,'发布服务',{
            '取消':function () {
                this.modal('hide');
            },
            '发布':function () {
                var self = this,
                    version = $('#version-select').val();
                var statusMap = {
                    EM_I_NOT_START  : '未开始',
                    EM_I_RUNNING  : '执行中',
                    EM_I_SUCCESS  : '成功',
                    EM_I_FAILED  : '失败',
                    EM_I_CANCEL  : '取消',
                    EM_I_PARIAL : '部分成功'
                };
                if(!version){
                    showErrorMsg($box,'请选择发布版本');
                    return;
                }
                chks.each(function () {
                    var tmp={};
                    tmp.server_id = $(this).val();
                    tmp.command = 'patch_tars';
                    tmp.parameters = {patch_id:version,bak_flag:$(this).data('bak'),update_text:$.trim($('#comment').val())};
                    paramArr.push(tmp);
                });
                paramObj.serial = true;
                paramObj.items = paramArr;
                showLoading();
                var param = $.stringify(paramObj);
                $.ajax('/pages/server/api/add_task',{
                    contentType:'application/json',
                    method:'post',
                    data:param,
                    dataType:'json',
                    success:function (data) {
                        removeLoading();
                        if(data.ret_code==200){
                            var $dlg = $('#dlg-ret');
                            self.modal('hide');
                            /*var tableStr = '<table class="table"><caption>任务ID：'+data.data.task_no+'</caption><thead><tr><th>节点</th><th>状态</th></tr></thead><tbody>';
                            $.each(data.data.items,function (index,n) {
                                tableStr += '<tr><td>'+n.node_name+'</td><td class="curr-status">'+statusMap[n.status_info]+'</td></tr>';
                            });
                            tableStr += '</tobdy></table>';
                            $dlg.html(tableStr);
                            $('.curr-status').each(function () {
                                getTaskStatus(data.data.task_no,$(this));
                            });*/
                            getTaskStatus(data.data.task_no,$dlg);
                            showDialog($dlg,'发布结果');
                        }else{
                            showErrorMsg($box,'服务发布失败:'+data.err_msg);
                        }
                    }
                });
            }
        },700);
    }



</script>
</body>
</html>
